package com.tianyi.exception;

import org.springframework.util.StringUtils;

/**
 * @Author tianyi
 * @Description 异常的处理
 * @Date 2022 - 11 - 05
 **/
public class ApplicationException extends RuntimeException {
    /**
     * errorCode
     */
    private int errorCode; // 错误编码
    private String message; // 错误信息
    private int httpStatus; // http的返回状态

    String DEFAULT_MESSAGE = "Unknow Error";
    int DEFAULT_HTTPSTATUS = 200;

    /**
     * 构建函数
     */
    public ApplicationException() {
        super();
    }

    /**
     * 传入错误编号，这个应当很使用用
     * @param errorCode
     */
    public ApplicationException(int errorCode) {
        super();
        this.errorCode = errorCode;
        this.message = RestMsgEnum.getMessageByCode(errorCode);
    }

    public ApplicationException(int errorCode, String message) {
        super();
        this.errorCode = errorCode;
        this.message = message;
    }

    public ApplicationException(int errorCode, String message, int httpStatus) {
        super();
        this.errorCode = errorCode;
        this.message = message;
        this.httpStatus = httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * {@code cause} is <i>not</i> automatically incorporated in
     * this runtime exception's detail message.
     *
     * @param errorCode the error Code.
     * @param cause     the cause (which is saved for later retrieval by the
     *                  {@link #getCause()} method).  (A <tt>null</tt> value is
     *                  permitted, and indicates that the cause is nonexistent or
     *                  unknown.)
     * @since 1.4
     */
    public ApplicationException(int errorCode, Throwable cause) {
        super( cause);

        this.errorCode = errorCode;
        this.message = cause.getMessage();
    }


    public int getErrorCode() {
        return errorCode;
    }

    @Override
    public String getMessage() {
        if (StringUtils.isEmpty(this.message)) {
            return errorCode + "." + DEFAULT_MESSAGE;
        }
        return  this.message;
    }

    public int getHttpStatus() {
        if (httpStatus > 0) {
            return httpStatus;
        }
        return DEFAULT_HTTPSTATUS;
    }
}
